<template>
  <el-card class="box-card">
    <el-card class="box-card">
      <el-form label-width="80px">
        <el-form-item
          v-for="attr in work.workrelattrs.filter(v=>v.value)"
          :key="attr.name"
          :label="attr.name"
        >
          <el-input v-model="attr.value" :readonly="!editableAttrEditable||!attr.editable" />
        </el-form-item>
        <el-form-item label="附件">
          <el-button
            v-for="attach in work.attachments"
            :key="attach.uid"
            type="text"
            @click="displayAttachment(id, attach.path)"
          >{{ attach.name }}</el-button>
          <el-button
            v-if="work.attachments===undefined||work.attachments.length===0"
            type="text"
            disabled
          >无附件</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-if="'parts' in work && work.parts.length !== 0" class="box-card">
      <el-form :disabled="!partsEditable">
        <el-form-item v-for="part in work.parts" :key="part.uid" :label="part.type">
          {{ part.id }}
          <el-select
            v-model="partSelect[part.uid]"
            :placeholder="'请选择' + part.type"
            style="width: 190px"
            class="filter-item"
            value-key="uid"
            clearable
            @change="onChangePartSelect(partSelect[part.uid], part.alterparts)"
          >
            <el-option
              v-for="item in part.alterparts"
              :key="item.uid"
              :label="item.relattrs.名称 + '/' + item.relattrs.Id"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card">
      <el-form label-width="80px">
        <el-form-item label="人员">
          <!-- <el-input v-model="currentexecuteresult.name" type="text" disabled="true"/> -->
          <el-select
            v-model="selectedUser"
            placeholder="执行人"
            style="width: 190px"
            class="filter-item"
          >
            <el-option
              v-for="executor in executors"
              :key="executor.name"
              :label="executor.name"
              :value="executor.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="实施情况">
          <el-switch
            v-model="currentexecuteresult.decision"
            :disabled="!executeResultEditable"
            :active-text="currentexecuteresult.decision"
            active-value="已实施"
            inactive-value="未实施"
          />
          <!-- <el-select
            :disabled="!executeResultEditable"
            v-model="currentexecuteresult.decision"
            placeholder="实施情况"
            clearable
            style="width: 190px"
            class="filter-item"
          >
            <el-option
              v-for="decision in ['已实施','未实施']"
              :key="decision"
              :label="decision"
              :value="decision"
            />
          </el-select>-->
        </el-form-item>
        <el-form-item label="执行时间">
          <el-date-picker
            :disabled="!executeResultEditable"
            v-model="currentexecuteresult.date"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
            align="right"
          />
        </el-form-item>
        <el-form-item label="实际工时">
          <el-input
            :disabled="!executeResultEditable"
            v-model="currentexecuteresult.workhour"
            type="number"
          >
            <template slot="append">小时</template>
          </el-input>
        </el-form-item>
        <el-form-item label="拍照留证">
          <el-button
            :disabled="!executeResultEditable"
            class="filter-item"
            type="primary"
            icon="el-icon-picture-outline"
            @click="pickPhotoFromLibrary(id)"
          >选择照片</el-button>
          <el-container class="main">
            <el-card
              v-for="photoObject of photoObjectsForCurrentExecutor"
              :key="photoObject.name"
              :body-style="{ padding: '0px'}"
              class="attachment"
            >
              <img
                :id="photoObject.name"
                :src="photoObject.dataURL"
                :filename="photoObject.name"
                class="image"
                @click="displayPhoto"
              >
            </el-card>
          </el-container>
        </el-form-item>
        <el-form-item type="textarea" label="备注">
          <el-input :disabled="!executeResultEditable" v-model="currentexecuteresult.comment" />
        </el-form-item>
      </el-form>
    </el-card>
    <div class="filter-container" style="margin-top: 20px;">
      <!-- :disabled="!executeFinishButtonEditable" -->
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-circle-check-outline"
        @click="saveExecution(false)"
      >保存执行</el-button>
    </div>
  </el-card>
</template>

<script>
import { getUsername } from '@/utils/auth'
import { getWorkcard, saveWorkcard } from '@/utils/storage'
import { showFile, prepareToDisplay } from '@/utils/file'
import pickPhoto from '@/utils/camera'
import { parseTime } from '@/utils'

export default {
  name: 'WorkInstruction',
  props: {
    work: {
      default: () => {},
      type: Object
    },
    role: {
      type: String,
      default: ''
    },
    workuid: {
      type: String,
      default: ''
    },
    editable: {
      type: Boolean,
      default: true
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      partSelect: this.getPartSelect(),
      selectedUser: '',
      cachedexecuteresult: [],
      currentexecuteresult: {},
      photoObjects: [],
      photoObjectsForCurrentExecutor: [],
      executors: [],
      // executeFinishButtonEditable: true,
      executeFinishButtonEditable: false,
      editableAttrEditable: false,
      partsEditable: true,
      executeResultEditable: false,
      revisable: true
    }
  },
  watch: {
    role: {
      handler: function(newValue, oldValue) {
        this.prepareExecutors()
        this.currentexecuteresult = this.getDefaultExecuteResult()
        this.preparePhotoObjectsForCurrentExecutor(
          this.currentexecuteresult.photos
        )
      },
      deep: true
    },
    photoObjects: {
      handler: function(newValue, oldValue) {
        console.log(
          '[WorkInstruction]-[watch-photoObject]-newValue: ' +
            JSON.stringify(newValue)
        )
        this.currentexecuteresult.photos = this.getPhotos(newValue)
        this.photoObjectsForCurrentExecutor = newValue
        console.log(
          '[WorkInstruction]-[watch-photoObject]-currentexecuteresult: ' +
            JSON.stringify(this.currentexecuteresult)
        )
      },
      deep: true
    },
    executors: {
      handler: function(newValue, oldValue) {
        this.currentexecuteresult = this.getDefaultExecuteResult()
        console.log('mounted:' + JSON.stringify(this.currentexecuteresult))
        this.preparePhotoObjectsForCurrentExecutor(
          this.currentexecuteresult.photos
        )
        this.executeFinishButtonEditable = this.isExecuteFinishButtonEditable()
        this.executeResultEditable = this.isExecuteResultEditable()
        this.editableAttrEditable = this.isEditableAttrEditable()
        this.partsEditable = this.isPartsEditable()
        this.selectedUser = this.currentexecuteresult.name
      },
      deep: true
    },
    selectedUser: {
      handler: function(newValue, oldValue) {
        this.currentexecuteresult = this.getExecuteResult(newValue)
        this.preparePhotoObjectsForCurrentExecutor(
          this.currentexecuteresult.photos
        )
        this.executeFinishButtonEditable = this.isExecuteFinishButtonEditable()
        this.executeResultEditable = this.isExecuteResultEditable()
        this.editableAttrEditable = this.isEditableAttrEditable()
        this.partsEditable = this.isPartsEditable()
      },
      deep: true
    },
    editable: {
      handler: function(newValue, oldValue) {
        this.executeFinishButtonEditable = this.isExecuteFinishButtonEditable()
        this.executeResultEditable = this.isExecuteResultEditable()
        this.editableAttrEditable = this.isEditableAttrEditable()
        this.partsEditable = this.isPartsEditable()
      },
      deep: true
    },
    work: {
      handler: function(newValue, oldValue) {
        console.log('[WorkInstruction]-[watch]-work:')
        console.log(newValue)
        this.currentexecuteresult = this.getExecuteResult(this.selectedUser)
        this.preparePhotoObjectsForCurrentExecutor(
          this.currentexecuteresult.photos
        )
        this.executeFinishButtonEditable = this.isExecuteFinishButtonEditable()
        this.executeResultEditable = this.isExecuteResultEditable()
        this.editableAttrEditable = this.isEditableAttrEditable()
        this.partsEditable = this.isPartsEditable()
        this.cachedexecuteresult = []
      },
      deep: true
    }
  },
  mounted: function() {
    if (this.executors.length === 0) {
      this.prepareExecutors().then(executors => {
        this.selectedUser = this.getDefaultExecuteResult().name
      })
    }
  },
  methods: {
    getExecuteResult(username) {
      const that = this
      let executeresult = {}

      if (this.work.executeresult.length !== 0) {
        const executeresults = this.work.executeresult.filter(
          v => v.role === that.role
        )
        if (executeresults.length !== 0) {
          executeresult = executeresults.find(
            v => v.name.indexOf(username) !== -1
          )
          if (executeresult) {
            return executeresult
          }
        }
      }

      if (username.indexOf(getUsername()) !== -1) {
        executeresult = this.getCachedExecuteResult()
        if (executeresult) {
          return executeresult
        }
      }

      executeresult = {}
      executeresult.role = that.role
      executeresult.decision = '未实施'
      executeresult.date = ''
      executeresult.comment = ''
      executeresult.executestatus = '未执行'
      executeresult.workhour = '0'
      executeresult.photos = []

      const userObj = this.executors.find(v => v.name.indexOf(username) !== -1)

      executeresult.name = userObj && userObj.name

      if (userObj && userObj.name.indexOf(getUsername()) !== -1) {
        this.putToCache(executeresult)
      }

      return executeresult
    },

    getDefaultExecuteResult() {
      const that = this
      let executeresult = {}
      const username = getUsername()

      if (this.work.executeresult.length !== 0) {
        const executeresults = this.work.executeresult.filter(
          v => v.role === that.role
        )
        if (executeresults.length !== 0) {
          executeresult = executeresults.find(
            v => v.name.indexOf(username) !== -1
          )
          if (!executeresult) {
            executeresult = executeresults[0]
          }
          return executeresult
        }
      }

      executeresult = this.getCachedExecuteResult()
      if (executeresult) {
        return executeresult
      }

      executeresult = {}
      executeresult.role = that.role
      executeresult.decision = '未实施'
      executeresult.date = ''
      executeresult.comment = ''
      executeresult.executestatus = '未执行'
      executeresult.workhour = '0'
      executeresult.photos = []

      const myself = this.executors.find(v => v.name.indexOf(username) !== -1)
      if (myself) {
        executeresult.name = myself.name
        this.putToCache(executeresult)
      } else if (this.executors.length > 0) {
        executeresult.name = this.executors[0].name
      } else {
        executeresult.name = ''
      }

      return executeresult
    },
    getCachedExecuteResult() {
      const that = this
      let executeresult
      if (this.cachedexecuteresult.length !== 0) {
        executeresult = this.cachedexecuteresult.find(v => v.role === that.role)
      }
      return executeresult
    },
    isExecuteFinishButtonEditable() {
      const username = getUsername()
      if (
        this.executors.filter(v => v.name.indexOf(username) !== -1).length === 0
      ) {
        return false
      }

      if (
        this.currentexecuteresult.name &&
        this.currentexecuteresult.name.indexOf(username) === -1
      ) {
        return false
      }
      if (!this.editable) {
        return false
      }
      return true
    },
    isEditableAttrEditable() {
      const username = getUsername()
      if (this.role !== '工作者') {
        return false
      }

      if (
        this.executors.filter(v => v.name.indexOf(username) !== -1).length === 0
      ) {
        return false
      }

      if (!this.editable) {
        return false
      }

      return true
    },
    isPartsEditable() {
      const username = getUsername()

      if (
        this.currentexecuteresult.name &&
        this.currentexecuteresult.name.indexOf(username) === -1
      ) {
        return false
      }

      if (!this.editable) {
        return false
      }

      if (this.role !== '工作者') {
        return false
      }

      return true
    },
    isExecuteResultEditable() {
      const username = getUsername()

      if (
        this.executors.filter(v => v.name.indexOf(username) !== -1).length === 0
      ) {
        return false
      }

      if (
        this.currentexecuteresult.name &&
        this.currentexecuteresult.name.indexOf(username) === -1
      ) {
        return false
      }

      if (!this.editable) {
        return false
      }

      return true
    },
    cloneExecuteResult(executeResult) {
      return {
        role: executeResult.role,
        name: executeResult.name,
        decision: executeResult.decision,
        date: executeResult.date,
        comment: executeResult.comment,
        executestatus: executeResult.executestatus,
        workhour: executeResult.workhour,
        photos: executeResult.photos
      }
    },
    putToCache(executeresult) {
      const existOne = this.cachedexecuteresult.find(
        v => v.role === executeresult.role
      )
      if (existOne) {
        existOne.name = executeresult.name
        existOne.decision = executeresult.decision
        existOne.date = executeresult.date
        existOne.comment = executeresult.comment
        existOne.executestatus = executeresult.executestatus
        existOne.workhour = executeresult.workhour
        existOne.photos = executeresult.photos
      } else {
        this.cachedexecuteresult.push(executeresult)
      }
    },
    putToWorkExecuteresult(executeresult) {
      const existOne = this.work.find(v => v.role === executeresult.role)
      if (existOne) {
        existOne.name = executeresult.name
        existOne.decision = executeresult.decision
        existOne.date = executeresult.date
        existOne.comment = executeresult.comment
        existOne.executestatus = executeresult.executestatus
        existOne.workhour = executeresult.workhour
        existOne.photos = executeresult.photos
      } else {
        this.cachedexecuteresult.push(executeresult)
      }
    },
    saveExecution(handle = false) {
      console.log('我执行了', handle)
      const that = this
      getWorkcard(this.workuid)
        .then(workcard => {
          return new Promise((resolve, reject) => {
            if (workcard && 'workcard' in workcard) {
              const _workcard = workcard.workcard
              const workinstruction = _workcard.workinstructions.find(
                v => v.id === that.work.id
              )

              that.currentexecuteresult.executestatus = '已执行'
              that.currentexecuteresult.date = that.currentexecuteresult.date
                ? that.currentexecuteresult.date
                : parseTime(new Date())

              const executeresult = workinstruction.executeresult.find(
                v => v.role === that.currentexecuteresult.role
              )
              if (!executeresult) {
                workinstruction.executeresult.push(that.currentexecuteresult)
              } else {
                executeresult.name = that.currentexecuteresult.name
                executeresult.decision = that.currentexecuteresult.decision
                executeresult.date = that.currentexecuteresult.date
                  ? that.currentexecuteresult.date
                  : parseTime(new Date())
                executeresult.comment = that.currentexecuteresult.comment
                executeresult.executestatus =
                  that.currentexecuteresult.executestatus
                executeresult.workhour = that.currentexecuteresult.workhour
                executeresult.photos = that.currentexecuteresult.photos
              }

              workinstruction.executeresult = workinstruction.executeresult.filter(
                v =>
                  !(
                    v.role === that.currentexecuteresult.role &&
                    v.name !== that.currentexecuteresult.name
                  )
              )

              workinstruction.parts = that.work.parts

              that.work.executeresult = workinstruction.executeresult

              resolve(_workcard)
            } else {
              reject(new Error('工卡格式不正确，请重新下载工卡！'))
              console.log(workcard)
            }
          })
        })
        .then(workcard => {
          saveWorkcard(workcard)
        })
        .then(() => {
          if (!handle) {
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
          }
        })
        .catch(err => {
          console.log(err)
          this.$message({
            message: '保存失败！' + err,
            type: 'error'
          })
        })
    },
    displayAttachment(id, path) {
      showFile(id, path)
    },
    pickPhotoFromLibrary(id) {
      const that = this
      pickPhoto(id)
        .then(photos => {
          that.photoObjects = photos
        })
        .catch(err => {
          console.log(err)
        })
    },
    displayPhoto(event) {
      const fileName = event.target.getAttribute('fileName')
      console.log('[WorkInstruction]-[displayPhoto]-fileName: ' + fileName)
      console.log('[WorkInstruction]-[displayPhoto]-id: : ' + this.id)
      showFile(this.id, fileName)
    },
    preparePhotoObjectsForCurrentExecutor(photos) {
      const that = this
      const photoPromise = []
      photos.forEach(photo => {
        console.log(
          '[WorkInstruction]-[preparePhotoObjects]-fileName: ' + photo.path
        )
        photoPromise.push(prepareToDisplay(that.id, photo.path))
      })
      Promise.all(photoPromise)
        .then(photoObjs => {
          that.photoObjectsForCurrentExecutor = []
          photoObjs.forEach(photoObj => {
            that.photoObjectsForCurrentExecutor.push(photoObj)
          })
        })
        .catch(e => {
          console.log(
            '[WorkInstruction]-[preparePhotoObjectsForCurrentExecutor]-Prepare to display error: ' +
              JSON.stringify(e)
          )
        })
    },
    prepareExecutors() {
      const that = this
      return getWorkcard(this.workuid)
        .then(workcard => {
          return new Promise((resolve, reject) => {
            if (workcard && 'workcard' in workcard) {
              const _workcard = workcard.workcard
              that.executors = _workcard.executors.filter(
                v => v.role === that.role
              )

              resolve(that.executors)
            } else {
              reject(new Error('工卡格式不正确，请重新下载工卡！'))
              console.log(workcard)
            }
          })
        })
        .catch(err => {
          console.log(err)
        })
    },
    getPhotos(photoObjects) {
      const photos = []
      photoObjects.forEach(photoObject => {
        photos.push({
          uid: '',
          type: 'image',
          name: photoObject.name.substring(
            0,
            photoObject.name.lastIndexOf('.')
          ),
          path: photoObject.name
        })
      })
      return photos
    },
    onChangePartSelect(alterpart, alterparts) {
      alterparts.forEach(v => {
        v.selected = false
      })

      if (Object.prototype.toString.apply(alterpart) === '[object Object]') {
        alterpart.selected = true
      }

      console.log(
        '[WorkInstruction]-[onChangePartSelect]-alterpart: ' +
          JSON.stringify(alterpart)
      )
      console.log(
        '[WorkInstruction]-[onChangePartSelect]-alterparts: ' +
          JSON.stringify(alterparts)
      )
      console.log(
        '[WorkInstruction]-[onChangePartSelect]-work: ' +
          JSON.stringify(this.work)
      )
    },
    getPartSelect() {
      const partSelect = {}
      this.work.parts.forEach(part => {
        part.alterparts.forEach(alterpart => {
          if (alterpart.selected === true) {
            partSelect[part.uid] = alterpart
          }
        })
      })
      return partSelect
    }
  }
}
</script>

<style scoped>
.main {
  width: 100%;
  display: flex;
  display: -webkit-flex; /* Safari */
  flex-flow: row wrap;
  justify-content: flex-start;
  align-content: flex-start;
  align-items: flex-start;
  flex: auto;
  overflow: scroll;
}

.image {
  width: auto;
  height: 3rem;
  max-width: 100%;
  max-height: 100%;
  display: block;
}

.imagedisplay {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  display: block;
}

.attachment {
  margin: 0rem;
}
</style>
